package org.duang.kit;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.duang.config.Config;
import org.duang.upload.UploadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OSSKit {

	private static Logger logger = LoggerFactory.getLogger(OSSKit.class);
	
	public static boolean putObject(String key, String filePath){
		synchronized (OSSKit.class) {
			try {
				com.aliyun4j.core.OSSUtils.putObject("sytimg", key, filePath);
				return true;
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return false;
			}	
		}
	}
	
	/**
	 * OSS上传时，文件目录(key)不能还有/
	 * @param files
	 */
	public static void putImg2OSS(List<UploadFile> files) {
		String key = "", filePath = "", serverDir = "";
		for(Iterator<UploadFile> it = files.iterator(); it.hasNext();){
			UploadFile uploadFile = it.next();
			key = uploadFile.getServerFilePath();
			filePath = ToolsKit.getWebRootPath() + key;
			serverDir = uploadFile.getServerDirectory();
			File loaclFile = new File(filePath);
			File loaclDir = new File(ToolsKit.getWebRootPath() + serverDir);
			if(serverDir.indexOf(Config.getUploadFileServerRootDirectory()) > -1){
				serverDir = serverDir.replace(Config.getUploadFileServerRootDirectory(), "/img");
			}
			if(key.indexOf(Config.getUploadFileServerRootDirectory()) > -1){
				key = key.replace(Config.getUploadFileServerRootDirectory(), "img");
			}
			
			try {
				com.aliyun4j.core.OSSUtils.putObject("sytimg", key, filePath);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			uploadFile.setServerDirectory(serverDir);
			loaclFile.delete();
			loaclDir.delete();
		}
	}
	
}
